package com.wn55.hrms.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wn55.hrms.entity.Role;
import com.wn55.hrms.mapper.RoleMapper;
import com.wn55.hrms.service.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;



/**
 * @author z
 */
@Service
public class RoleService {

    @Autowired
    RoleMapper roleMapper ;

    /**
     *
     * @param now
     * @param size
     * @param name
     * @return
     */
//    @Cacheable(value = "role",key = "#root.targetClass+#root.methodName+#root.args[0]+#root.args[1]+#root.args[2]")
    public PageInfo<RoleVo> roleList(Integer now, Integer size, String name){
        PageHelper.startPage(now,size);
        List<RoleVo> list = roleMapper.selectRoleByName(name);
        // 给每一个角色 查询他拥有的权限
        /*
          角色id --- > 角色和权限的中间表
         */
        for (RoleVo rv : list){
            List<Long> pids = roleMapper.selectPerIdByRoleId(rv.getId());
            rv.setPerIds(pids);
        }

        return new PageInfo<>(list);
    }

    public void modify(Role role) {
        roleMapper.update(role);
    }

    /**
     * @param role
     */
    @Transactional //加事务
    public void rolePermission(RoleVo role) {
        //1.删除当前角色的所有权限
        roleMapper.deletePermissionByRoleId(role.getId());
        List<Long> pids = new ArrayList<>();
        for (String sid :role.getCheckedPids().split(":")){
            pids.add(Long.parseLong(sid));
        }
        //2.插入新的权限
        roleMapper.insertRolePermission(role.getId(),pids);
    }

    public List<Role> queryAll() {
        return roleMapper.selectAll();
    }

    public void add(Role role) {
        roleMapper.insert(role);
    }


    @Transactional
    public void removeBykey(int id) {
        //1.  删除管理员和角色中间表的数据
        roleMapper.deleteManagerRoleByRoleId(id);
        //2  删除权限和 角色中间表的数据
        roleMapper.deletePerRoleByRoleId(id);
        //3 .  删除角色数据
        roleMapper.deleteByPrimaryKey((long) id);
    }
}
